import * as types from "../types/editUserInfoTypes";
import NetWorkUtil from "../utils/NetWorkUtil";
import { isEmpty } from "../utils/utils";
import ApiConstants from "../common/ApiConstants";
import { toastShort } from "../utils/ToastUtils";

export function uploadHeader(header_src) {
  return dispatch => {
    dispatch({ type: types.EDITUSERINFO_LOADING });
    NetWorkUtil.uploadPicture(header_src)
      .then(res => {
        toastShort("头像上传成功");
        dispatch({ type: types.EDITUSERINFO_UPLOAD_DONE, headerSrc: res });
      })
      .catch(error => {
        toastShort("头像上传失败");
        dispatch({ type: types.EDITUSERINFO_UPLOAD_ERROR, error });
      });
  };
}

export function saveUserInfo(nickname, header_src) {
  return dispatch => {
    if (isEmpty(nickname)) {
      toastShort("请输入新昵称");
      return;
    }
    dispatch({ type: types.EDITUSERINFO_LOADING });
    const params = { nickname, header_src: NetWorkUtil.getUploadHeaderUrl(header_src) };
    NetWorkUtil.post(ApiConstants.EDIT_USERINFO, params)
      .then(res => {
        toastShort("个人信息保存成功");
        dispatch({ type: types.EDITUSERINFO_DONE });
      })
      .catch(error => {
        toastShort("个人信息保存失败");
        dispatch({ type: types.EDITUSERINFO_ERROR, error });
      });
  };
}

export function inputName(nickname) {
  return dispatch => {
    dispatch({ type: types.EDITUSERINFO_INPUT_NAME, nickname });
  };
}

export function initEdit(nickname, header_src) {
  return dispatch => {
    dispatch({
      type: types.EDITUSERINFO_INIT,
      nickname,
      headerSrc: header_src,
    });
  };
}

export function editUserInfoUnmount() {
  return dispatch => {
    dispatch({ type: types.EDITUSERINFO_UNMOUNT });
  };
}
